package com.controller;

import java.util.Date;

import com.domain.AppUser;
import com.domain.EMailMessage;
import com.persistence.UserAccessObject;

public class UserManager {
	private EMailSender mailSender = new EMailSender();
	private UserAccessObject userDAO = new UserAccessObject();
	
	public boolean registerUser(String userName, String userPassword,String eMailAddress, Date registryDate){
		AppUser registeringUser = createUser(userName,userPassword,eMailAddress,registryDate);
		userDAO.insertObject(registeringUser);
		sendRegistrationMail(registeringUser);
		return true;
	}
	
	public boolean isUserValid(AppUser validatingUser){
		AppUser existingUser = searchAppUser(validatingUser.getUserName());
		boolean isValidUser = validateUser(existingUser,validatingUser);
		return isValidUser;
	}
	
	private boolean validateUser(AppUser existingUser, AppUser validatingUser){
		if(existingUser != null){
			return existingUser.getUserPassword().equalsIgnoreCase(validatingUser.getUserPassword());
		}
		return false;
	}
	
	public AppUser searchAppUser(String userName){
		AppUser searchedUser = userDAO.getObject(userName);
		return searchedUser;
	}
	
	private void sendRegistrationMail(AppUser registeringUser){
		EMailMessage sendingMail = createRegisteringMessage(registeringUser);
		mailSender.sendEmail(sendingMail);
	}
	
	private AppUser createUser(String userName, String userPassword,String emailAddress, Date registryDate){
		AppUser newUser = new AppUser(userName,userPassword,emailAddress,registryDate);
		return newUser;
	}
	
	private EMailMessage createRegisteringMessage(AppUser newUser){
		EMailMessage newMessage = new EMailMessage();
		String mailDestination = newUser.getUserEmailAddress();
		newMessage.setMailDestination(mailDestination);
		String messageBody = "You have succesfully registered to Where I Was Service";
		newMessage.setMessageBody(messageBody);
		String mailSubject = "Registration to Where I Was";
		newMessage.setMailSubject(mailSubject);
		String mailUser = newUser.getUserName();
		newMessage.setMailUser(mailUser);
		return newMessage;
	}
}
